<?php

class Media extends CActiveRecord {    
    /**
     * The followings are the available columns in table 'www_media':
     * @var integer $id
     * @var string $name
     * @var string $file_name
     * @var integer $file_size
     * @var string $saved_filename
     * @var integer $created
     * @var integer $updated
     */

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{media}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        $media_types = Yii::app()->params['media_types'];
        $types = '';
        foreach($media_types as $media_type) {
            foreach ($media_type as $tp) {
                $types .= substr($tp, 2, strlen($tp)) . ',';
            }
        }
        $types = substr($types, 0, -1);
        return array(
            array('file_size, created, updated', 'numerical', 'integerOnly' => true),
            array('file_name, file_name_pinyin, file_saved_path, picture_thumb_saved_path', 'length', 'max' => 200),
            array('file_saved_path', 'file', 'on' => 'insert',
                'allowEmpty' => false,
                'types' => $types,
                'maxSize' => 1024 * 1024 * 10,
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
        return array(
            // 所属分类
            'category' => array(self::BELONGS_TO, 'MediaCategory', 'category_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'Id',
            'category_id' => Yii::t('media', 'category_id'),
            'file_name' => Yii::t('media', 'file_name'),
            'file_size' => Yii::t('media', 'file_size'),
            'file_extension' => Yii::t('media', 'file_extension'),
            'file_saved_path' => Yii::t('media', 'file_saved_path'),
            'created' => Yii::t('common', 'created'),
            'updated' => Yii::t('common', 'updated'),
        );
    }

    /**
     * 获取 Media 对象显示链接
     * 如果是图片，则直接显示，如果是其他的内容，则提示下载
     */
    public function getBackendMediaObjectShowUrl() {
        if (in_array("*.{$this->file_extension}", Yii::app()->params['media_types']['picture'])) {
            return Yii::app()->createUrl('backend/media/show', array('id' => $this->id));
        } else {
            return Yii::app()->createUrl('backend/media/downloading', array('id' => $this->id));
        }
    }

    // 获取文件类型（扩展名首字母大写）
    public function getTypeTextFormat() {
        return ucwords($this->file_extension);
    }

    // 图片缩略图保存地址
    public function getPictureThumbSavedPath() {
        return dirname(Yii::app()->basePath) . '/upload/media/' . $this->picture_thumb_saved_path;
    }

    // 图片缩略图来源地址
    public function getPictureThumbSourcePath() {
        return (trim($this->picture_thumb_saved_path) != '')
            ? Yii::app()->request->baseUrl . '/upload/media/' . $this->picture_thumb_saved_path
            : '';
    }

    /**
     * get meida file saved path
     * @return string
     */
    public function getMediaSavedPath() {
        return Yii::getPathOfAlias('webroot')
            . Yii::app()->params['upload_directory']['media'] . $this->file_saved_path;
    }

    /**
     * get media file source
     */
    public function getMediaSourcePath() {
        return Yii::app()->request->baseUrl . Yii::app()->params['upload_directory']['media'] . $this->file_saved_path;
    }

    // 获取 media 文件图片，图片文件直接返回缩略图，非图片文件返回对应的图标
    public function getMediaIconSource() {
        $media_types = Yii::app()->params['media_types'];
        $ext = "*.{$this->file_extension}";
        $media_type = 'unknow';
        foreach ($media_types as $type => $exts) {
            if (in_array($ext, $exts)) {
               $media_type = $type;
               break;
            }
        }
        if ($media_type == 'picture') {
            $img = (trim($this->pictureThumbSourcePath) == '')
                ? $this->mediaSourcePath
                : $this->pictureThumbSourcePath;
        } else {
            $img = Yii::app()->baseUrl . '/assets/backend/images/mime/icon_'
                . $this->file_extension . '.png';
        }

        return $img;
    }

    public function getUpdatedFormatted() {
        return ($this->updated) ? date('Y-m-d', $this->updated) : '';
    }

    // formatted file size to KB
    public function getFileSizeFormatKB() {
        return $this->file_size % 1024 . '&nbsp;KB';
    }

    // formatted file size to MB
    public function getFileSizeFormatMB() {
        return $this->file_size % (1024 * 1024) . '&nbsp;MB';
    }

    private $_original_file_saved_path;
    private $_original_file_name;
    public function afterFind() {
        $this->_original_file_saved_path = $this->file_saved_path;
        $this->_original_file_name = $this->file_name;
    }


    public function beforeValidate() {
        $uploading_file = CUploadedFile::getInstance($this, 'file_saved_path');
        if (is_object($uploading_file) && get_class($uploading_file) === 'CUploadedFile') {
            if (!$this->isNewRecord) {
                $config = Yii::app()->params['media_types']['picture'];
                // 更新记录的同时删除原上传文件，如果是图片文件的话，同时删除缩略图
                $model = Media::model()->findByPk($this->id);
                @unlink($model->mediaSavedPath);
                if (in_array("*.{$this->file_extension}", $config)) {
                    @unlink($this->pictureThumbSavedPath);
                }

                /**
                 * 　　判断更新上传的文件扩展名是否和当前上传文件的扩展名是否一致，
                 * 如果一致的话，则不修改 file_saved_path 的内容（如果是图片文件的话，
                 * 同时也不会修改 picture_thumb_file_path 的内容），上传文件名依旧使
                 * 用原文件名，而不再次生成。
                 * 　　比如原文件名为 123.jpg，此次更新上传的为 1.jpg，则 1.jpg 上传
                 * 之后的文件名不做改动，而如果此次更新上传的文件名为 1.png，则上传
                 * 之后的文件名重新生成。
                 * 　　这样做的作用是为了避免已经上传的文件被其他信息引用了话，如果
                 * 再次生成的文件名发生变化的话，则相应引用的地方都要做改动，这样会
                 * 无形中增加信息编辑工作量。不过这样的话，更新 media 文件的时候需要
                 * 上传者自己多加小心，以避免更新上传的文件和已经上传的文件不是一致
                 * 类型文件。
                 */
                $extension_name = strtolower($uploading_file->getExtensionName());
                $tmp = explode('.', $this->_original_file_saved_path);
                if (isset($tmp[1])) {
                    if ($tmp[1] == $extension_name) {
                        $file_saved_path = $this->_original_file_saved_path;
                        $file_name = $this->_original_file_name;
                    } else {
                        $file_saved_path = md5(time() . $uploading_file->getName()) . '.' . $extension_name;
                        $file_name = substr($uploading_file->getName(), 0,
                            strlen($uploading_file->getName()) - strlen($extension_name) - 1);
                    }
                }
                $this->file_saved_path = $file_saved_path;
                $this->file_name = $file_name;
//                $this->file_name = substr($uploading_file->getName(), 0,
//                    strlen($uploading_file->getName()) - strlen($extension_name) - 1);
                $this->file_extension = $extension_name;
                $this->file_size = $uploading_file->getSize();
                $uploading_file->saveAs(Yii::app()->basePath . '/../upload/media/' . $file_saved_path);
                // 如果是图片文件则生成对应的缩略图
                if (in_array("*.{$extension_name}", $config)) {
                    Yii::import('application.extensions.helper.CAppHelper');
                    $app_helper = new CAppHelper();
                    $picture_thumb_saved_path = $app_helper->generatePictureThumb(
                        Yii::getPathOfAlias('webroot') . Yii::app()->params['upload_directory']['media'],
                        $file_saved_path);
//                    echo $picture_thumb_saved_path;
                    $this->picture_thumb_saved_path = $picture_thumb_saved_path;
                }
            }
        } else {
            $this->file_saved_path = $this->_original_file_saved_path;
        }
        return true;
    }

    // 更新分类统计信息以及删除保存到文件
    public function afterDelete() {
        MediaCategory::model()->updateCounters(array('files_count' => -1), "id = {$this->category_id}");
        @unlink($this->mediaSavedPath);
        if (in_array("*.{$this->file_extension}", Yii::app()->params['media_types']['picture'])) {
            @unlink($this->pictureThumbSavedPath);
        }
    }

    // 生成图片选择的链接
//    public function getSelectPictureLink() {
//        return CHtml::link(CHtml::image(Yii::app()->baseUrl . '/assets/backend/images/select_picture.png', '', array('style' => 'verial-align: bottom; padding: 0; margin: 0px;')),
//            array('media/selectPicture'), array('class' => 'select_picture'));
//    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'created',
                'updateAttribute' => 'updated',
            )
        );
    }

    /**
     * 查询媒体文件
     * @param <string> $type
     * @param <integer> $category_id
     * @param <integer> $limit
     * @return AcitveRecord
     */
    public function findMedia($type, $category_id = 0, $limit = 10) {
        $criteria = new CDbCriteria();
        if (intval($category_id)) {
            $criteria->condition = "category_id = {$category_id}";
        }
        $criteria->limit = $limit;
        $criteria->order = 'created DESC';
        return Media::model()->findAll($criteria);
    }
}